/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package server;
//<editor-fold defaultstate="collapsed" desc=" các thư viện sử dụng">
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

/**
 *
 * @author KingofSpeed
 */
public class SetForeignKey extends javax.swing.JFrame {
//<editor-fold defaultstate="collapsed" desc=" properties">
    private String type;
    private String tableName;
    private String columnName;
    private MainWindow grandparent;
    CreateTableForm parent;
    DefaultListModel listReferenceColumnModel;
    DefaultListModel listForeignKeyModel;
     //</editor-fold >
    //<editor-fold defaultstate="collapsed" desc=" hàm khởi tạo với các thông số truyền vào">
    public SetForeignKey( CreateTableForm _parent, MainWindow _grandparent, String table, String column , List<String> key, String _type) {
        initComponents();
        grandparent = _grandparent;
        tableName = table;
        columnName = column;
        parent = _parent ;
        type = _type;
        lTableName.setText(table);
        lColumnName.setText(column);
        listReferenceColumnModel = new DefaultListModel();
        listForeignKeyModel = new DefaultListModel();
        listReferenceColumn.setModel(listReferenceColumnModel);
        listForeignKey.setModel(listForeignKeyModel);
        LoadTableName();
        for ( int i = 0; i < key.size(); i++ )
            listForeignKeyModel.addElement(key.get(i));
    }
     //</editor-fold >
//<editor-fold defaultstate="collapsed" desc=" load các bảng vào combo box">
    public void LoadTableName()
    {
        cbTableName.removeAllItems();
        for( int i = 0; i < grandparent.dataTables.size(); i++ )
        {
            cbTableName.addItem(grandparent.dataTables.get(i).getName());
        }
        if (grandparent.listTable.size()>0)
            GetTableColumn(0 );
        cbTableName.addActionListener(new TableNameSelectionChanged());
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
     //</editor-fold >
    //<editor-fold defaultstate="collapsed" desc=" Code generated = design">
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        listReferenceColumn = new javax.swing.JList();
        jScrollPane2 = new javax.swing.JScrollPane();
        listForeignKey = new javax.swing.JList();
        rightToLeft = new javax.swing.JButton();
        leftToRight = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        lTableName = new javax.swing.JLabel();
        lColumnName = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        cbTableName = new javax.swing.JComboBox();
        bOk = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        listReferenceColumn.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        listReferenceColumn.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane1.setViewportView(listReferenceColumn);

        listForeignKey.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        listForeignKey.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        jScrollPane2.setViewportView(listForeignKey);

        rightToLeft.setIcon(new javax.swing.ImageIcon(getClass().getResource("/SourceImage/LeftNormal.png"))); // NOI18N
        rightToLeft.setToolTipText("Remove Selected Column");
        rightToLeft.setContentAreaFilled(false);
        rightToLeft.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                rightToLeftMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                rightToLeftMouseExited(evt);
            }
        });
        rightToLeft.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rightToLeftActionPerformed(evt);
            }
        });

        leftToRight.setIcon(new javax.swing.ImageIcon(getClass().getResource("/SourceImage/RightNormal.png"))); // NOI18N
        leftToRight.setToolTipText("Add Column");
        leftToRight.setContentAreaFilled(false);
        leftToRight.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                leftToRightMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                leftToRightMouseExited(evt);
            }
        });
        leftToRight.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                leftToRightActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel1.setText("Table :");

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel2.setText("Column :");

        lTableName.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        lTableName.setText("jLabel3");

        lColumnName.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        lColumnName.setText("jLabel3");

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel3.setText("Foreign Key :");

        cbTableName.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        bOk.setIcon(new javax.swing.ImageIcon(getClass().getResource("/SourceImage/OkNormal.png"))); // NOI18N
        bOk.setToolTipText("Ok, Close");
        bOk.setContentAreaFilled(false);
        bOk.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                bOkMouseEntered(evt);
            }
            public void mouseExited(java.awt.event.MouseEvent evt) {
                bOkMouseExited(evt);
            }
        });
        bOk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bOkActionPerformed(evt);
            }
        });

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel4.setText("Reference Table :");

        jLabel5.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel5.setText("Reference Columns :");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(29, 29, 29)
                        .addComponent(lTableName))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addGap(18, 18, 18)
                        .addComponent(lColumnName))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(jLabel4)
                                .addGap(18, 18, 18)
                                .addComponent(cbTableName, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addComponent(jLabel5)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(rightToLeft, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(bOk, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(leftToRight, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 226, javax.swing.GroupLayout.PREFERRED_SIZE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(lTableName))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(lColumnName))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cbTableName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 232, Short.MAX_VALUE)
                    .addComponent(jScrollPane1)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(leftToRight, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(5, 5, 5)
                                .addComponent(rightToLeft, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(bOk, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel5)
                                .addGap(0, 0, Short.MAX_VALUE)))
                        .addContainerGap())))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void rightToLeftMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_rightToLeftMouseEntered
        ImageIcon ii = new ImageIcon(this.getClass().getResource("/SourceImage/LeftClick.png"));
        rightToLeft.setIcon(ii);
    }//GEN-LAST:event_rightToLeftMouseEntered

    private void rightToLeftMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_rightToLeftMouseExited
        ImageIcon ii = new ImageIcon(this.getClass().getResource("/SourceImage/LeftNormal.png"));
        rightToLeft.setIcon(ii);
    }//GEN-LAST:event_rightToLeftMouseExited

    private void leftToRightMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_leftToRightMouseEntered
        ImageIcon ii = new ImageIcon(this.getClass().getResource("/SourceImage/RightClick.png"));
        leftToRight.setIcon(ii);
    }//GEN-LAST:event_leftToRightMouseEntered

    private void leftToRightMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_leftToRightMouseExited
        ImageIcon ii = new ImageIcon(this.getClass().getResource("/SourceImage/RightNormal.png"));
        leftToRight.setIcon(ii);
    }//GEN-LAST:event_leftToRightMouseExited

    private void bOkMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bOkMouseEntered
        ImageIcon ii = new ImageIcon(this.getClass().getResource("/SourceImage/OkClick.png"));
        bOk.setIcon(ii);
    }//GEN-LAST:event_bOkMouseEntered

    private void bOkMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_bOkMouseExited
        ImageIcon ii = new ImageIcon(this.getClass().getResource("/SourceImage/OkNormal.png"));
        bOk.setIcon(ii);
    }//GEN-LAST:event_bOkMouseExited

    private void leftToRightActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_leftToRightActionPerformed
        try
        {
            int selected = listReferenceColumn.getSelectedIndex();
            String columnname = String.valueOf(listReferenceColumn.getSelectedValue());
            if ( columnname.equals("null") == false )
            {
                listForeignKeyModel.addElement(String.valueOf(cbTableName.getSelectedItem()) + "_" + columnname );
                listReferenceColumnModel.remove(selected);
            }
        }
        catch ( Exception ex ){}
    }//GEN-LAST:event_leftToRightActionPerformed

    private void rightToLeftActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rightToLeftActionPerformed
        try
        {
            String se = String.valueOf(listForeignKey.getSelectedValue());
            listForeignKeyModel.remove(listForeignKey.getSelectedIndex());
            RefreshTableColumn();
        }
        catch ( Exception ex ){}
    }//GEN-LAST:event_rightToLeftActionPerformed

    private void bOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bOkActionPerformed
        Save();
        this.dispose();
    }//GEN-LAST:event_bOkActionPerformed
    
    
    /**
     * @param args the command line arguments
     */
     //</editor-fold >
  //<editor-fold defaultstate="collapsed" desc=" biến generated = design">
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bOk;
    private javax.swing.JComboBox cbTableName;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JLabel lColumnName;
    private javax.swing.JLabel lTableName;
    private javax.swing.JButton leftToRight;
    private javax.swing.JList listForeignKey;
    private javax.swing.JList listReferenceColumn;
    public javax.swing.JButton rightToLeft;
    // End of variables declaration//GEN-END:variables
     //</editor-fold >
    //<editor-fold defaultstate="collapsed" desc=" Save lại các khóa ngoại khi nhấn ok">
    public void Save()
    {
        if ( parent.type == 0 )
            grandparent.dataTables.remove(grandparent.dataTables.size() - 1);
        ArrayList<String> tam = new ArrayList<String>();
        for ( int i = 0; i < listForeignKeyModel.size(); i++)
        {
            tam.add(listForeignKeyModel.get(i).toString());
        }
        parent.SaveForeignKey( columnName, tam);
    }
     //</editor-fold >
    //<editor-fold defaultstate="collapsed" desc=" lấy các cột trong bảng được chọn ở combo box">
    public void GetTableColumn( int index )
    {
        String tName = grandparent.dataTables.get(index).getName();
        for ( int j = 0; j < grandparent.dataTables.get(index).getListColumn().size(); j++  )
        {
            boolean isTonTai = false;
            for ( int i = 0; i < listForeignKeyModel.size(); i++ )
            {
                if ( GetNameFromForeignKey( i, true ).equals(tName)
                        && GetNameFromForeignKey( i, false ).equals(grandparent.dataTables.get(index).getListColumn().get(j).getTitle()))
                {
                    isTonTai = true;
                    break;
                }
            }
            if ( isTonTai == false && grandparent.dataTables.get(index).getListColumn().get(j).getType().equals(type))
                listReferenceColumnModel.addElement(grandparent.dataTables.get(index).getListColumn().get(j).getTitle());
        }
    }
     //</editor-fold >
    //<editor-fold defaultstate="collapsed" desc=" lấy tên bảng tên cột từ khóa ngoại">
    public String GetNameFromForeignKey( int index, boolean getTableName )
    {
        String result[];
        try
        {
            if ( index >= 0 )
            {
                result = String.valueOf(listForeignKeyModel.get(index)).split("_");
                if ( getTableName == true )
                    return result[0];
                else if ( getTableName == false )
                    return result[1];
            }
            return "";
        }
        catch ( Exception ex ){ return "";}
                
    }
     //</editor-fold >
    //<editor-fold defaultstate="collapsed" desc=" duyệt lại các cột sau khi một số đã được dùng làm khóa">
    public void RefreshTableColumn()
    {
        for ( int i = 0; i <  grandparent.dataTables.size(); i++)
            {
                if ( grandparent.dataTables.get(i).getName().equals(String.valueOf(cbTableName.getSelectedItem())) )
                {
                    listReferenceColumnModel.removeAllElements();
                    GetTableColumn( i );
                    break;
                }
            }
    }
     //</editor-fold >
    //<editor-fold defaultstate="collapsed" desc=" xử lí sự kiện thay đổi bảng chọn trong combo box">
    class TableNameSelectionChanged implements ActionListener
    {
        @Override
        public void actionPerformed(ActionEvent e) { 
             RefreshTableColumn();
        }
        
    }
     //</editor-fold >
    //<editor-fold defaultstate="collapsed" desc=" hàm hiển thị các thông báo">
    public void ShowMessageBox ( String ms , String l )
    {
        if ( "Error".equals(l))
             JOptionPane.showMessageDialog( this, ms, "Lỗi", JOptionPane.ERROR_MESSAGE);
        else if ( "Success".equals(l))
            JOptionPane.showMessageDialog( this, ms, "Thành Công", JOptionPane.INFORMATION_MESSAGE);
        else
            JOptionPane.showMessageDialog( this, ms, "Thông Báo", JOptionPane.PLAIN_MESSAGE);
    }
     //</editor-fold >
}
